package com.homework.reflect.test;
import com.homework.reflect.bean.Student;
import org.junit.Test;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.time.LocalDateTime;

/**
 * @author nmm
 * @date 2024-03-2024/3/25
 * @deriction 两种方式创建对象并用set方法对实例化的对象进行赋值
 */
public class StudentReflectTest2 {

    @Test
    public void testclazzset() throws Exception {
        Class  StuClass = Class.forName("com.homework.reflect.bean.Student");
        Student student = (Student) StuClass.newInstance();//创建对象
//        Class StuClass = Student.class;
//        Constructor specificCons = StuClass.getConstructor(String.class, Integer.class, String.class, LocalDateTime.class, String.class);//通过指定参数列表来获取具体的构造方法
//        Object objstu1 = specificCons.newInstance("nmm胡图图", 18, "男", LocalDateTime.now(), "翻斗花园26号");

//        Field name = StuClass.getDeclaredField("name");
//        Field age = StuClass.getDeclaredField("age");
//        Field sex = StuClass.getDeclaredField("sex");
//        Field address = StuClass.getDeclaredField("address");
//        Field stuDate = StuClass.getDeclaredField("stuDate");//获取名字为stuDate的属性
//
//        System.out.println(stuDate.getName());//属性名
//        System.out.println(stuDate.getType().getName());//属性类型
//
//
//        name.setAccessible(true);
//        age.setAccessible(true);
//        sex.setAccessible(true);
//        address.setAccessible(true);
//        stuDate.setAccessible(true);//设置属性stuDate访问修饰符为public
//
//
//        name.set(student,"土豆damn🥔");
//        age.set(student,18);
//        sex.set(student,"男");
//        address.set(student,"翻斗花园26号");
//        stuDate.set(student,LocalDateTime.now());//通过公开属性值调用其set方法对对象进行实例化
//        System.out.println(student);
        //麻烦....



        Object []params={"寄生",18,"男",LocalDateTime.now(),"同创牛子谷🐂D栋325"};
        //通过拿到所有属性值实例化对象
        Field[]  propertyFields = StuClass.getDeclaredFields();
        for (int i = 0; i < propertyFields.length; i++) {
            String propertyName=propertyFields[i].getName();     //获取属性名
            Class<?> propertyType = propertyFields[i].getType();//获取具体属性类型
            String setMethodName="set"+propertyName.toUpperCase().charAt(0)+propertyName.substring(1);//获取set方法名
            Method  setMethod = StuClass.getDeclaredMethod(setMethodName, propertyType);//通过指定具体的set方法名和属性类型来获取具体set方法
            setMethod.invoke(student, params[i]);//通过set方法对创建的对象进行赋值(对象实例,参数值)
        }
        System.out.println(student);

    }
}